<template>
  <el-dialog v-model="dialogVisible" width="900" :before-close="handleClose">
      <template #header>
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" alt="Logo" />
          <span class="titleClass">查看详情</span>
        </div>
      </template>
      <el-form label-width="auto" :model="diaFrom" :disabled="dialogDisable" style="height: 600px;">
        <el-form-item  style="height: 100%;">
            <div style="height: 100%; overflow: auto; width: 100%;">
                <template v-if="isCompressedFile(files.url)">
                    <div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%;">
                        <p style="font-size: 18px; color: #ff4d4f;">无法预览压缩文件</p>
                        <p style="font-size: 16px; color: #606266;">文件名: {{ getfilename(files.url) }}</p>
                    </div>
                </template>
                <template v-else>
                    <component :is="getPreviewComponent(files)" :src="files.url" style="height: 100%;"></component>
                </template>
            </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div v-if="files.status === 0 || checkRole()">
            <el-button type="primary" @click="download(files.url)">下载附件</el-button>
            <el-button type="warning" @click="oepnRejectDialog(files)">拒绝</el-button>
            <el-button type="success" @click="passApply(files.id)">通过</el-button>
          </div>
        </div>
      </template>
  </el-dialog>
  <Reject ref="rejectDialog" @refreshChild = "refresh"></Reject>
</template>

<script setup>
import { ref, defineEmits, provide} from 'vue';
import { useUserStore } from "@/store";
import { ElMessage } from 'element-plus';
import pdfViewer from '@vue-office/pdf'
import docxViewer from '@vue-office/docx'
import excelViewer from '@vue-office/excel'
import { saveAs } from 'file-saver';
import Reject from './Reject.vue';
import { AdminDetermine } from '../../api/announcement';

const dialogVisible = ref(false);
const files = ref([]);
const rejectDialog = ref(null)
const userStore = useUserStore();
const emit = defineEmits(["refreshList"])

function checkRole() {
  if (userStore.userRole.includes("ROLE_ADMIN")) {
    // console.log("这不是没有嘛", userStore.userRole);
    return true;
  }
  return false;
}

const oepnRejectDialog = (files) =>{
    provide("refreshChild",refresh)
    rejectDialog.value.openDialog(files);
}

const showAttachments = async (id, value) => {
    console.log("已经到子组件里了")
    try {
        const fetchedFiles = value
        console.log('Fetched Files:', fetchedFiles); // 调试输出
        files.value = fetchedFiles;
        dialogVisible.value = true;
    } catch (error) {
        ElMessage.error('获取附件失败');
    }
};

const handleClose = () => {
  dialogVisible.value = false;
};

// 动态选择预览组件
const getPreviewComponent = (file) => {
    const fileType = getFileType(file.url);
    switch (fileType) {
        case 'excel':
            return excelViewer;
        case 'pdf':
            return pdfViewer;
        case 'docx':
            return docxViewer;
        default:
            return iframe; // 默认返回图片查看组件
    }
};

const getfilename = (url) => {
    const name = url.split('/').pop();
    return name;
}

const isCompressedFile = (fileName) => {
  const compressedExtensions = ['zip', 'rar', '7z', 'tar', 'gz', 'bz2'];
  const extension = fileName.split('.').pop().toLowerCase();
  return compressedExtensions.includes(extension);
};

// 获取文件类型
const getFileType = (filename) => {
  const extension = filename.split('.').pop().toLowerCase();
  if (['jpg', 'jpeg', 'png', 'gif'].includes(extension)) return 'image';
  if (extension === 'pdf') return 'pdf';
  if (['docx', 'doc'].includes(extension)) return 'docx';
  if (extension === 'xlsx')return 'excel'
  if (['zip', 'rar', '7z'].includes(extension)) return 'zip'
  // 可以继续添加其他文件类型的判断
  return 'unknown';
};

const download = (url) => {
    try{
        // const extent = getFileType(url)
        saveAs(url,"附件")
    }
    catch(eroor){
        console.log(error)
    }
}

const passApply = async (id) =>{
    try{
        const fd = new FormData();
        console.log("filesId:" + id)
        fd.append("ApplicationId", id);
        fd.append("isPass", true);
        await AdminDetermine(fd);
        dialogVisible.value = false
        refresh();
        ElMessage.success("认定成功")
    }
    catch(error){
        ElMessage.error("认定失败");
    }
}

const refresh = async() => {
    handleClose();
    emit('refreshList')
}


// 导出 showAttachments 方法
defineExpose({ showAttachments });
</script>

<style scoped lang="scss">
.my-header {
  display: flex;
  height: 50px;
  line-height: 50px;

  .titleClass {
    font-size: 25px;
  }
  .imgtitle {
    width: 50px;
    height: 50px;
    margin-right: 10px;
  }
  .titleendClass {
    margin-left: 10px;
    font-size: 20px;
  }
}
.attachments {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 70%;
}
.attachment-item {
  border: 1px solid #ddd;
  padding: 16px;
  border-radius: 4px;
  font-size: 16px;
  text-align: left; /* 左对齐文本 */
}
.attachment-item a {
  color: #1890ff; /* 链接颜色 */
  text-decoration: none; /* 移除下划线 */
}
.attachment-item a:hover {
  text-decoration: underline; /* 鼠标悬停时显示下划线 */
}
</style>